import json
import time
import socket

udp_ip = "127.0.0.1"
udp_port = 12201
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def process(line):
  try:
    data = json.loads(line)
    result = {
      "domain": data["transaction"]["request"]["headers"]["Host"],
      "dst_ip": data["transaction"]["host_ip"],
      "dst_port": data["transaction"]["host_port"],
      "forward": "0.0.0.0",
      "matched": data["transaction"]["messages"][0]["details"]["data"],
      "host": socket.gethostname(),
      "message": socket.gethostname(),
      "method": data["transaction"]["request"]["method"],
      "msg": data["transaction"]["messages"][0]["message"],
      "req_header": data["transaction"]["request"]["headers"],
      "retcode": data["transaction"]["response"]["http_code"],
      "rsp_header": data["transaction"]["response"]["headers"],
      "rule_id": data["transaction"]["messages"][0]["details"]["ruleId"],
      "severity": data["transaction"]["messages"][0]["details"]["severity"],
      "source": data["transaction"]["host_ip"],
      "src_ip": data["transaction"]["client_ip"],
      "src_port": data["transaction"]["client_port"],
      "url": data["transaction"]["request"]["uri"]
    }
    send_udp(json.dumps(result))
  except json.JSONDecodeError as e:
    print(f"Error decoding JSON: {e}")
  except KeyError as e:
    print(f"Missing key in JSON data: {e}")

def send_udp(message):
  sock.sendto(message.encode('utf-8'), (udp_ip, udp_port))

def tail_f(file):
  with open(file, 'r') as f:
    f.seek(0, 2)  # 移动文件指针到文件末尾
    while True:
      line = f.readline()
      if not line:
        time.sleep(1)  # 如果没有新行，等待1秒后再检查
        continue
      process(line)

if __name__ == "__main__":
  log_file_path = "/var/log/modsec_audit.log"
  tail_f(log_file_path)

